package com.wenwei.net;

import android.util.Log;


import com.wenwei.parking.BaseApplication;

import java.io.IOException;
import java.util.Locale;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/10/8.
 */
public class LogInterceptor implements Interceptor {
    public static final String TAG = "LogInterceptor.java";
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        //the request url
        String url = request.url().toString();
        //the request method
        String method = request.method();
        long t1 = System.nanoTime();
        Log.d(TAG,String.format(Locale.getDefault(),"Sending %s request [url = %s]",method,url));
        if (!NetworkUtil.isNetworkAvailable(BaseApplication.getAppContext())) {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .url(url).build();
        }
        Response response = chain.proceed(request);
        if (!NetworkUtil.isNetworkAvailable(BaseApplication.getAppContext())) {
            int maxAge = 60 * 60; // read from cache for 1 minute
            response.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .build();
        } else {
            int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
            response.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }

        return response;
    }
}